# coding: utf-8
# @Author: cyl
# @File: 03func.py
# @Time: 2024/07/03 20:24:51
# 文件头
from typing import Self

"""1、普通函数"""
def abc(bc, a=10) -> int:
    return 123

# : int >>> 注解
# String abc = "123456"
# abc = 123456 (错误)
def add(x: int) -> int | str | None | tuple:
    y = x + 1
    return y

# def abc(a: A, x: int) -> int:
#     return a.add(x)


# 方法跟函数的共同点和区别
class Foo:
    body: str = '123'

    def __new__(cls: type[Self]) -> Self:
        pass

    def __init__(self):
         self.name="haiyan"

    # 方法: 只能通过类或类的实例调用
    def func(self):
         print(self.name)
    
    # 静态方法
    @staticmethod
    def add():
        return 10
    
    # 类方法: 单例（数据库连接、redis连接）
    @classmethod
    def sub1(cls):
        print(cls.body)
        return 20
    
    def sub2(self):
         return 20
        
    def sub3(self, num1: int, num2: int, num3: int) -> int:
        return num1 + num2 + num3
    
    # python：解包, 面试问的比较多
    # 必传参数写在前面, 非必要的就放在kwargs
    # *args 是一个元组
    # **kwargs 是一个字典
    """
    request_params: dict = {
        "access-token": "123", 必填
        "keep_alive": True     非必填
    }
    """
    def sub4(self, access_token: str, **kwargs) -> int:
        num4, num5 = kwargs.get("num4", 10), kwargs.get("num50", 20)
        new_params: dict = {
            "access-token": access_token
        }
        keep_alive: any = kwargs.get("keep_alive")
        if keep_alive:
            new_params["keep_alive"] = keep_alive
        return new_params

    # def request_handler(self, method: str, url: str, **kwargs):
    #     return requests.request(method=method, url=url, **kwargs)




obj = Foo()
obj.func()
obj.add()
obj.sub1()
obj.sub2()
print(obj.sub4("adbhakdhwaddawd", num4=100, num5=2000)) # {'access-token': 'adbhakdhwaddawd'}
print(obj.sub4("adbhakdhwaddawd", num4=100, num5=2000, keep_alive=True)) # {'access-token': 'adbhakdhwaddawd', 'keep_alive': True}


"""2、闭包函数: 语法糖"""
def abc():
    def wrapper():
        print(123)
        return wrapper
    return wrapper
# eg1: 类的每个方法执行中我都需要查看他的执行时间
# eg2: 真实场景 -> 有部分接口在master 和 dev是不同的, master上有些服务的接口是不需要调用的, dev测试环境就需要调用
# dev开发环境 test/qa/release测试环境(qa1 qa2 qa3...) uat预生产(模拟真实环境) master生产


"""3、匿名函数 lambda"""
def square(x):
    return x ** 2
print(square(10)) # 100

square2Def = lambda x: x**2
print(square2Def(100)) # 10000
